#include "../Headers/tConfigTemplate.hpp"
#include "../Headers/tLogger.hpp"
#include "../Headers/tFile.hpp"
#include "../Headers/tFormatter.hpp"

#include "Libs/md5/md5.h"

using namespace std;

string makeCheckSum(string contentIn) {
	int lastNotLineBreak = contentIn.find_last_not_of('\n');
	contentIn = contentIn.substr(0, lastNotLineBreak);
	string ret = md5(contentIn.substr(0, lastNotLineBreak));

	return ret;
}

wstring makeCheckSum(wstring contentIn) {
	int lastNotLineBreak = contentIn.find_last_not_of('\n');
	contentIn = contentIn.substr(0, lastNotLineBreak);
	string retStr = md5(contentIn.c_str(), contentIn.length() * sizeof(wchar_t));

	wstring retWStr = TFormater::string2wstring(retStr);

	return retWStr;
}

string TConfigTools::addIntegrityCheckSum(string profilePlainTxt) {
	if (profilePlainTxt.back() != '\n') {
		profilePlainTxt += "\n";
	}
	string tail = makeCheckSum(profilePlainTxt);
	string content = profilePlainTxt + tail;
	//bool flag = checkProfileIntegrity(content, profilePlainTxt);
	return content;
}

wstring TConfigTools::addIntegrityCheckSum(wstring profilePlainTxt) {
	if (profilePlainTxt.back() != '\n') {
		profilePlainTxt += L"\n";
	}
	wstring tail = makeCheckSum(profilePlainTxt);
	wstring content = profilePlainTxt + tail;
	//bool flag = checkProfileIntegrity(content, profilePlainTxt);
	return content;
}

bool splitProfileContent(string& input, string& plainTextOut, string& checkSumOut) {
	size_t pos = input.find_last_of('}');
	if (pos == string::npos) {
		return false;
	}
	plainTextOut = input.substr(0, pos + 1);
	// line break
	checkSumOut = input.substr(pos + 2);
	return true;
}

bool splitProfileContent(wstring& input, wstring& plainTextOut, wstring& checkSumOut) {
	size_t pos = input.find_last_of('}');
	if (pos == string::npos) {
		return false;
	}
	if (pos == input.length() - 1) {
		plainTextOut = input;
		checkSumOut = L"";
		return true;
	}
	plainTextOut = input.substr(0, pos + 1);
	// line break
	checkSumOut = input.substr(pos + 2);
	return true;
}

//string str0, str1, str2, str3;

bool TConfigTools::checkIntegrity(string profileStrFull, string& plainTxtOut) {
	string checkSum;
	if (splitProfileContent(profileStrFull, plainTxtOut, checkSum)) {
		//if (checkersss) {
		//	int stop = 1;
		//}
		string plainTextMd5 = makeCheckSum(plainTxtOut);

		if (plainTextMd5.compare(checkSum) == 0) {
			return true;
		}
		else {
			TLogger::writeLine("Checksum Not Match");
		}
	}
	else {
		TLogger::writeLine("Splitting profile text error");
	}
	return false;
}

bool TConfigTools::checkIntegrity(wstring profileStrFull, wstring& plainTxtOut) {
	wstring checkSum;
	if (splitProfileContent(profileStrFull, plainTxtOut, checkSum)) {
		//if (checkersss) {
		//	int stop = 1;
		//}
		wstring plainTextMd5 = makeCheckSum(plainTxtOut);

		if (plainTextMd5.compare(checkSum) == 0) {
			return true;
		}
		else {
			TLogger::writeLine("Checksum Not Match");
		}
	}
	else {
		TLogger::writeLine("Splitting profile text error");
	}
	return false;
}
